import axios from "axios";
import router from "@/router";
import store from "@/store";
import { Loading, Message } from "element-ui";
import whiteMenuArr from "@/utils/testapiwhitemenu";
import { getToken, clearCache } from "@/utils/public";
import crypto from "@/crypto";
import { randomWord } from "@/utils/getRandom";

const http = axios.create({
  baseURL: "/merchantApi",
  timeout: 1000 * 60,
  withCredentials: true,
});

let loadingObj = null;
/**
 * 请求拦截
 */
http.interceptors.request.use(
  (config) => {
    if (
      config.url != "/menu/listMenuByUser" &&
      config.url != "/menu/getSpecialOperationButton" &&
      config.url != "/api/dict/channelList" &&
      config.url != "/api/dict/payTypeList" &&
      config.url != "/sys/meal/listMeal" &&
      config.url != "/sys/message/count" &&
      config.url != "/sys/user/refreshCurrentUser"
    ) {
      loadingObj = Loading.service({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
    }
    // loadingObj = Loading.service({
    //   lock: true,
    //   text: "Loading",
    //   spinner: "el-icon-loading",
    //   background: "rgba(0, 0, 0, 0.7)",
    // });
    //   config.headers['token'] = localStorage.get('token') || ''
    // loadingObj = Loading.service({
    //     lock: true,
    //     text: 'Loading',
    //     spinner: 'el-icon-loading',
    //     background: 'rgba(0, 0, 0, 0.7)'
    // });
    // console.log(store.state, '---');
    // console.log(Math.floor((Math.random()*[8,9,10,11,12].length)))
    // console.log([8,9,10,11,12][Math.floor((Math.random()*[8,9,10,11,12].length))])
    let len = [8, 9, 10, 11, 12][
      Math.floor(Math.random() * [8, 9, 10, 11, 12].length)
    ];
    // console.log(len);
    // console.log(randomWord(len));
    // console.log(randomWord([8,9,10,11,12][Math.floor((Math.random()*[8,9,10,11,12].length))]).length)
    let curTmp = new Date().getTime();
    config.headers["auth_token"] = getToken();
    config.headers["auth_tmp"] = curTmp;
    config.headers["auth_tck"] = crypto.set(
      getToken() + "_" + curTmp + "_" + randomWord(len),
      "a1g0qoalvv19aed3"
    );
    if (
      store.state.menuType === 1 &&
      router.currentRoute.path != "/middleWork" &&
      router.currentRoute.path != "/companyPersonInfo" &&
      router.currentRoute.path != "/editCompanyPersonInfo" &&
      router.currentRoute.path != "/message" &&
      router.currentRoute.path != "/advice" &&
      router.currentRoute.path != "/downCenter"&&
      router.currentRoute.path != "/login"
    ) {
    config.headers["app_id"] = store.state.appId;
      //支持test模式（应用内）
      if (store.state.testLine) {
        //前端开启test
        var url = config.url;
        if (url.indexOf("?") != -1) {
          url = url.replace(/(\?|#)[^'"]*/, ""); //去除参数
          //console.log(url);
        }
        let wlink = whiteMenuArr.find((item) => item == url);
        if (wlink) {
          //属于白名单
          //console.log("应用-test模式");
          //console.log(url);
          config.headers["api_mode"] = "test";
        } else {
          //console.log(url + "-不支持");
          store.commit("changeTestMode", true);
          config.headers["api_mode"] = "live";
        }
      } else {
        //console.log("应用-live模式");
        config.headers["api_mode"] = "live";
      }
    } else {
      store.commit("changeTestMode", false);
      store.commit("changeTestLine", false);
    }

    // 默认参数
    // var defaults = {}
    // 防止缓存，GET请求默认带_t参数
    // if (config.method === 'get') {
    //   config.params = {
    //     ...config.params,
    //     // ...{ '_t': new Date().getTime() }
    //   }
    // }
    // if (config.params) {
    //   config.params = {
    //     ...defaults,
    //     ...config.params
    //   }
    // }
    // if (config.data) {
    //   config.data = {
    //     ...defaults,
    //     ...config.data
    //   }
    //   // if (/^application\/x-www-form-urlencoded/.test(config.headers['content-type'])) {
    //   //   config.data = qs.stringify(config.data)
    //   // }
    // }
    return config;
  },
  (error) => {
    if (loadingObj) {
      loadingObj.close();
    }
    return Promise.reject(error);
  }
);

/**
 * 响应拦截
 */
http.interceptors.response.use(
  (response) => {
    if (loadingObj) {
      loadingObj.close();
    }
    if (response.data.code === "0000") {
      return response.data;
    } else {
      if (response.data.code&&response.config.url!='/api/merchant/settleaccount/add') {
        Message.closeAll();
        Message({
          message: response.data.msg,
          type: "error",
        });
      }
      if (response.data.code === "0401") {
        // clearLoginInfo()
        clearCache();
        router.replace({ name: "loginVue" });
        return Promise.reject(response.data.msg);
      }
      return response.data;
    }
  },
  (error) => {
    if (loadingObj) {
      loadingObj.close();
    }
    console.error(error);
    Message.closeAll();
    Message({
      message: "系统繁忙，请稍后再试",
      type: "error",
    });
    return Promise.reject(error);
  }
);

export default http;
